<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          v-loading="formLoading"
        >
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="formData.userId" clearable placeholder="请输入用户ID" />
          </el-form-item>
          <el-form-item label="流程编号" prop="processInstanceId">
            <el-input v-model="formData.processInstanceId" clearable placeholder="请输入流程编号" />
          </el-form-item>
          <el-form-item label="申报类型" prop="type">
            <el-select v-model="formData.type" clearable placeholder="请选择申报类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CX_FORM_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              clearable
              type="datetime"
              value-format="x"
              placeholder="选择开始时间"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              clearable
              type="datetime"
              value-format="x"
              placeholder="选择结束时间"
            />
          </el-form-item>
          <el-form-item label="机构名字" prop="agencyName">
            <el-input v-model="formData.agencyName" clearable placeholder="请输入机构名字" />
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8">
        <div style="padding: 0 20px 0">
          <span style="font-weight:bold;line-height:32px;">审批流程</span>
          <ProcessInstanceTimeline
            ref="timelineRef"
            :activity-nodes="activityNodes"
            :show-status-icon="false"
            @select-user-confirm="selectUserConfirm"
          />
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeclarationInfoApi, DeclarationInfoVO } from '@/api/bpm/declarationinfo'

// 审批相关
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'

defineOptions({ name: 'DeclarationInfoForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  userId: undefined,
  processInstanceId: undefined,
  type: undefined,
  startTime: undefined,
  endTime: undefined,
  agencyName: undefined
})
const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  processInstanceId: [{ required: true, message: '流程编号不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '申报类型不能为空', trigger: 'change' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
  agencyName: [{ required: true, message: '机构名字不能为空', trigger: 'blur' }]
})
const formRef = ref()

// 审批相关变量
const processDefineKey = 'cx_declaration_info' // 流程定义 Key，需根据实际流程定义调整
const startUserSelectTasks = ref<any[]>([])
const startUserSelectAssignees = ref<Record<string, any[]>>({})
const tempStartUserSelectAssignees = ref<Record<string, any[]>>({})
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([])
const processDefinitionId = ref('')

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeclarationInfoApi.getDeclarationInfo(id)
    } finally {
      formLoading.value = false
    }
  }
  // 审批相关：加载流程定义和审批节点
  await loadProcessDefinitionAndApproval()
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择${userTask.name}的审批人`)
      }
    }
  }
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeclarationInfoVO
    // 审批相关：设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      (data as any).startUserSelectAssignees = startUserSelectAssignees.value
    }
    if (formType.value === 'create') {
      await DeclarationInfoApi.createDeclarationInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeclarationInfoApi.updateDeclarationInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    processInstanceId: undefined,
    type: undefined,
    startTime: undefined,
    endTime: undefined,
    agencyName: undefined
  }
  formRef.value?.resetFields()
}

// 审批相关：加载流程定义和审批节点
const loadProcessDefinitionAndApproval = async () => {
  // 获取流程定义
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(undefined, processDefineKey)
  if (!processDefinitionDetail) {
    message.error('申报流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
  // 加载审批详情
  await getApprovalDetail()
}

// 审批相关：获取审批详情
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({}) // 可根据业务需要传递变量
    })
    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    activityNodes.value = data.activityNodes
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {}
}

// 审批相关：选择发起人
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

// 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) return
    if (newValue && Object.keys(newValue).length > 0) {
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      getApprovalDetail()
    }
  },
  { immediate: true }
)
</script>
